package com.fbt.transfer.app.driver.ui.index;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.fbt.transfer.app.driver.R;
import com.fbt.transfer.app.driver.databinding.FragmentIndexBinding;
import com.fbt.transfer.app.driver.model.index.OrderUnitVo;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.List;

public class IndexFragment extends Fragment {

  private FragmentIndexBinding binding = null;
  private IndexViewModel viewModel = null;
  private TabLayoutMediator tabLayoutMediator = null;

  // 标签页标题
  private final String[] tabTitles = new String[]{"今日任务", "待办任务"};

  @Override
  public View onCreateView (@NonNull LayoutInflater inflater,
      ViewGroup container, Bundle savedInstanceState) {
    viewModel = new ViewModelProvider(this).get(IndexViewModel.class);

    binding = FragmentIndexBinding.inflate(inflater, container, false);
    View root = binding.getRoot();
    initViewPager();
    initTabLayout();
    observeViewModel();

    // 加载初始数据
    viewModel.loadTodayOrders(true);
    viewModel.loadTomorrowOrders(true);

    return root;
  }

  private void initViewPager () {
    // 设置ViewPager2适配器
    binding.viewPager.setAdapter(new FragmentStateAdapter(this) {
      @NonNull
      @Override
      public Fragment createFragment (int position) {
        // 根据位置创建对应的订单列表Fragment
        return OrderListFragment.newInstance(position == 0);
      }

      @Override
      public int getItemCount () {
        return tabTitles.length;
      }
    });

    // 确保ViewPager2可以水平滑动
    binding.viewPager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
    binding.viewPager.setUserInputEnabled(true);

    // 设置页面切换监听
    binding.viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
      @Override
      public void onPageSelected (int position) {
        super.onPageSelected(position);
        // 当页面切换时，可以在这里处理一些逻辑
      }
    });
  }

  private void initTabLayout () {
    // 将TabLayout和ViewPager2关联起来
    tabLayoutMediator = new TabLayoutMediator(binding.tabLayout, binding.viewPager,
                                              (tab, position) -> {
                                                // 设置Tab的文本
                                                if (position == 0) {
                                                  // 今日任务标签
                                                  viewModel.getTodayOrderCountLiveData()
                                                      .observe(
                                                          getViewLifecycleOwner(), count -> tab.setText(
                                                              tabTitles[position] + " (" + count + ")"));
                                                } else {
                                                  // 待办任务标签
                                                  viewModel.getTomorrowOrderCountLiveData()
                                                      .observe(
                                                          getViewLifecycleOwner(), count -> tab.setText(
                                                              tabTitles[position] + " (" + count + ")"));
                                                }
                                              }
    );
    tabLayoutMediator.attach();
  }

  private void initStatsView () {
    View statsView = getView().findViewById(R.id.index_stats_view);
    // 观察统计数据变化并更新UI
    viewModel.getIndexStatsLiveData().observe(getViewLifecycleOwner(), indexStats -> {
      if (indexStats != null) {
        TextView tvTodayIncome = statsView.findViewById(R.id.tv_today_income);
        TextView tvTodayFinishedCount = statsView.findViewById(R.id.tv_today_finished_count);
        TextView tvTodayCount = statsView.findViewById(R.id.tv_today_count);
        TextView tvWaitCount = statsView.findViewById(R.id.tv_wait_count);

        tvTodayIncome.setText(indexStats.getTodayIncome().stripTrailingZeros().toPlainString());
        tvTodayFinishedCount.setText(String.valueOf(indexStats.getTodayFinishedCount()));
        tvTodayCount.setText(String.valueOf(indexStats.getTodayCount()));
        tvWaitCount.setText(String.valueOf(indexStats.getWaitCount()));
      }
    });
  }

  private void observeViewModel () {
    // 观察错误信息
    viewModel.getErrorLiveData().observe(getViewLifecycleOwner(), errorMsg -> {
      if (getActivity() != null && !getActivity().isFinishing() && isResumed()) {
        Toast.makeText(getContext(), errorMsg, Toast.LENGTH_SHORT).show();
      }
    });
  }

  @Override
  public void onViewCreated (@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    initStatsView();
  }

  @Override
  public void onDestroyView () {
    super.onDestroyView();
    if (tabLayoutMediator != null) {
      tabLayoutMediator.detach();
    }
    binding = null;
  }

  /**
   * 订单列表Fragment，用于显示今日任务或待办任务
   */
  public static class OrderListFragment extends Fragment {

    private boolean isToday = true;
    private OrderInfoAdapter adapter = null;
    private IndexViewModel viewModel = null;
    private View statsView = null;
    private boolean isLoading = false;

    public static OrderListFragment newInstance (boolean isToday) {
      OrderListFragment fragment = new OrderListFragment();
      Bundle args = new Bundle();
      args.putBoolean("isToday", isToday);
      fragment.setArguments(args);
      return fragment;
    }

    @Override
    public void onCreate (@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      if (getArguments() != null) {
        isToday = getArguments().getBoolean("isToday", true);
      }
    }

    @Nullable
    @Override
    public View onCreateView (@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fragment_order_list, container, false);
      viewModel = new ViewModelProvider(requireParentFragment()).get(IndexViewModel.class);
      initRecyclerView(view);
      initSwipeRefresh(view);
      observeViewModel();
      return view;
    }

    private void initSwipeRefresh (View view) {
      SwipeRefreshLayout swipeRefreshLayout = view.findViewById(
          R.id.swipe_refresh_layout);
      swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
      swipeRefreshLayout.setOnRefreshListener(() -> {
        // 根据当前标签页刷新数据
        if (isToday) {
          viewModel.loadTodayOrders(true);
        } else {
          viewModel.loadTomorrowOrders(true);
        }
      });

      // 观察加载状态，控制刷新动画
      viewModel.getLoadingLiveData().observe(getViewLifecycleOwner(), swipeRefreshLayout::setRefreshing);
    }

    private void initRecyclerView (View view) {
      RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
      adapter = new OrderInfoAdapter(this, getContext());
      recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
      recyclerView.setAdapter(adapter);
      // 设置滚动监听，实现上拉加载更多
      recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled (@NonNull RecyclerView recyclerView, int dx, int dy) {
          super.onScrolled(recyclerView, dx, dy);

          LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
          if (layoutManager != null) {
            int visibleItemCount = layoutManager.getChildCount();
            int totalItemCount = layoutManager.getItemCount();
            int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

            // 判断是否滑动到底部，并且不是正在加载，并且不是最后一页
            if (!isLoading && (visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                && firstVisibleItemPosition >= 0) {
              isLoading = true;

              // 根据当前标签页加载更多数据
              if (isToday) {
                if (!viewModel.isLastTodayPage()) {
                  viewModel.loadNextTodayPage();
                }
              } else {
                if (!viewModel.isLastTomorrowPage()) {
                  viewModel.loadNextTomorrowPage();
                }
              }
            }
          }
        }
      });
    }


    private void observeViewModel () {
      // 观察加载状态
      viewModel.getLoadingLiveData().observe(getViewLifecycleOwner(), loading -> isLoading = loading);

      // 根据当前标签页观察对应的数据
      if (isToday) {
        // 观察今日任务数据
        viewModel.getTodayOrdersLiveData().observe(getViewLifecycleOwner(), this::handleOrderList);

        // 观察空数据状态
        viewModel.getEmptyTodayDataLiveData().observe(getViewLifecycleOwner(), isEmpty -> {
          View emptyView = getView().findViewById(R.id.empty_view);
          RecyclerView recyclerView = getView().findViewById(R.id.recycler_view);

          if (isEmpty) {
            recyclerView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
          } else {
            recyclerView.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
          }
        });
      } else {
        // 观察待办任务数据
        viewModel.getTomorrowOrdersLiveData().observe(getViewLifecycleOwner(), this::handleOrderList);

        // 观察空数据状态
        viewModel.getEmptyTomorrowDataLiveData().observe(getViewLifecycleOwner(), isEmpty -> {
          View emptyView = getView().findViewById(R.id.empty_view);
          RecyclerView recyclerView = getView().findViewById(R.id.recycler_view);

          if (isEmpty) {
            recyclerView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
          } else {
            recyclerView.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
          }
        });
      }
    }

    private void handleOrderList (List<OrderUnitVo> orderList) {
      if (!orderList.isEmpty()) {
        adapter.setData(orderList);
      }
    }
  }
}